/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zornav.file;

import com.transas.zornav.data.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author amalikov
 */
public class TaskDataSourceReader implements DataSourceReader {
	private final static Logger LOG = Logger.getLogger(TaskDataSourceReader.class.getName());

	@Override
	public void process(Reader file, DataSource ds) {
		try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Element root = db.parse(new InputSource(file)).getDocumentElement();
			Element node = (Element)root.getElementsByTagName("points").item(0);
			NodeList pointList = node.getElementsByTagName("point");
			
			int n = ds.getSize();
			for (int i = 0; i < pointList.getLength(); ++i) {
				Node point = pointList.item(i);
				NamedNodeMap attr = point.getAttributes();
				double lat = Double.parseDouble(attr.getNamedItem("latitude").getNodeValue());
				double lon = Double.parseDouble(attr.getNamedItem("longitude").getNodeValue());
				double alt = Double.parseDouble(attr.getNamedItem("height").getNodeValue());
				ds.addRow();
				ds.setValue(ds.getHandle("N"), n + i, n + i);
				ds.setValue(ds.getHandle("Latitude"), n + i, lat);
				ds.setValue(ds.getHandle("Longitude"), n + i, lon);
				ds.setValue(ds.getHandle("Altitude"), n + i, alt);
			}
		} catch (SAXException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
	}
	
}
